<template>
  <el-dialog
    top="30px"
    width="500px"
    append-to-body
    :title="`还款计划（${repayFunds} 万元）`"
    class="dialog-sm"
    :close-on-click-modal="false"
    :before-close="onRepayListDismiss"
    :visible.sync="visible"
  >
    <table class="table table-bordered table-sm text-center table-vertical-middle m-0">
      <thead>
        <tr>
          <th width="45%">还款时间</th>
          <th width="55%">本金(元)</th>
          <!-- <th width="33%">利息(元)</th> -->
        </tr>
      </thead>
      <tr
        v-for="(p, index) of repayList"
        v-loading="loading"
        :class="{ 'tr-current': currentRow === index }"
        @click="handleRowClick(index)"
        :key="index"
      >
        <td :class="tdClass">
          <span v-if="isViewMode">
            {{ $utils.dateFormat(p.pay_time, 'yyyy年MM月dd日') }}
          </span>
          <el-date-picker
            v-else
            v-model="p.pay_time"
            type="date"
            class="w-100 text-center"
            value-format="yyyy-MM-dd"
            format="yyyy年MM月dd日"
            :clearable="false"
            :placeholder="`选择${index === 0 ? '开始' : ''}还款时间`"
          ></el-date-picker>
        </td>
        <td :class="tdClass">
          <span v-if="isViewMode">
            {{ p.capital || '-' }}
          </span>
          <div class="d-flex align-items-center" v-else>
            <el-input
              v-model="p.capital"
              placeholder="输入本金"
              v-input-number="{ min: 0, fixed: 2 }"
              class="flex-1 text-center"
            ></el-input>
            <div
              class="text-muted"
              title="自动填写到所有下面的列"
              @click="onAutoFill(p, index, 'capital')"
            >
              <i class="fa fa-fw fa-angle-double-down"></i>
            </div>
          </div>
        </td>
      </tr>
      <tr v-if="!repayList.length">
        <td colspan="3" class="text-muted">暂无还款计划</td>
      </tr>
    </table>
    <div class="row-sum border">
      <div class="row-sum-td">合计</div>
      <div class="row-sum-td">
        <span>{{ editSums }}</span>
      </div>
    </div>
    <div class="mt-1">
      <el-button-group class="mb-2" v-if="!isViewMode">
        <el-button size="small" @click="handleRowAdd">
          <i class="fa fa-indent"></i>
          添加一行
        </el-button>

        <el-button size="small" @click="handleRowDelete">
          <i class="fa fa-outdent"></i>
          删除当前行
        </el-button>
      </el-button-group>
    </div>
    <div class="pt-3 text-center" v-show="!isViewMode">
      <el-button class="btn-long" type="primary" @click="handleFinsh" :loading="saveLoading">
        保存
      </el-button>
      <el-button class="btn-long" @click="onRepayListDismiss">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, mul } from '@vimi/utils-tool'
export default {
  props: {
    visible: Boolean,
    queryId: String,
    viewMode: {
      type: Boolean,
      default: true,
    },
    repayFunds: {
      type: String,
      default: '0',
    },
  },
  data() {
    return {
      loading: false,
      dialogMaxheight: 400,
      repayList: [],
      currentRow: 0,
      saveLoading: false,
      deleteData: [],
      tableName: 'datum_repay_list',
    }
  },
  computed: {
    isViewMode() {
      return this.viewMode
    },
    tdClass() {
      return this.isViewMode ? '' : 'input-td'
    },
    editSums() {
      return this.getSums(this.repayList)
    },
    repayFundsYuan() {
      return mul(this.repayFunds, 1e4)
    },
  },
  watch: {
    visible: {
      handler: function () {
        if (this.visible) {
          this.getRepayList()
        }
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    async handleFinsh() {
      const repayListData = []
      for (const item of this.repayList) {
        if (item.pay_time) {
          if (!+item.capital) {
            return this.$message.warning('请输入还款金额')
          }
          if (+item.capital < +item.repay_funds_total) {
            return this.$message.warning(
              `${item.pay_time}还款金额不能小于已登记还款金额,请删除还款登记后重试`
            )
          }
          const data = {
            customer_related_id: this.queryId,
            pay_time: item.pay_time,
            capital: item.capital || '',
          }
          if (item.datum_repay_list_id) {
            data.datum_repay_list_id = item.datum_repay_list_id
          }
          repayListData.push(data)
        } else if (item.capital) {
          return this.$message.warning('请选择还款时间')
        } else if (item.datum_repay_list_id) {
          this.deleteData.push(item.datum_repay_list_id)
        }
      }
      if (this.editSums !== this.repayFundsYuan) {
        return this.$message.error(
          `还款计划本金合计金额（${this.editSums}元）与放款金额（${this.repayFundsYuan}元）不相等，请先调整还款计划！`
        )
      }
      this.saveLoading = true
      if (this.deleteData.length) {
        await this.$api.deleteData(this.$serviceName, this.tableName, this.deleteData.join(','))
      }

      await this.$api.updateBatch('credit', this.tableName, repayListData)

      this.saveLoading = false
      this.$message.success('保存成功')
      this.getRepayList()
      this.$emit('success', true)
      this.beforeClose()
    },
    tableRowClassName({ rowIndex }) {
      return this.currentRow === rowIndex ? 'tr-current' : ''
    },
    getRepayList() {
      if (!this.queryId) return
      this.repayList = []
      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          'datum_repay_list_view_new',
          {
            'customer_related_id.eq': this.queryId,
          },
          { pay_time: 'asc' }
        )
        .then(res => {
          const data = (res && res.data) || []
          if (data.length) {
            this.repayList = data.map(item => ({
              datum_repay_list_id: item.datum_repay_list_id,
              pay_time: item.pay_time,
              is_capital: item.is_capital,
              capital: item.capital,
              repay_funds_total: item.repay_funds_total, //已还金额
            }))
            this.$emit('getData', true)
          } else if (!this.viewMode) {
            this.$emit('getData', false)
            this.initRepayList()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    initRepayList() {
      this.repayList = [
        {
          pay_time: '',
          capital: '',
        },
      ]
    },
    getSums(list) {
      return list.reduce((a, b) => {
        return add(a, b.capital)
      }, 0)
    },
    onAutoFill(row, index, key) {
      for (let i = index; i < this.repayList.length; i++) {
        this.repayList[i][key] = row[key]
      }
    },

    onRepayListDismiss() {
      this.beforeClose()
    },

    handleRowAdd() {
      this.repayList.push({
        capital: '',
        pay_time: '',
      })
    },

    handleRowClick(index) {
      this.currentRow = index
    },

    handleRowDelete() {
      const len = this.repayList.length
      if (len < 2) {
        return
      }
      const data = this.repayList[this.currentRow]
      if (data.repay_funds_total > 0) {
        return this.$message.warning('还款计划已对应有还款登记不能删除')
      } else {
        if (data.datum_repay_list_id) {
          this.deleteData.push(data.datum_repay_list_id)
        }
        this.repayList.splice(this.currentRow, 1)
        if (this.currentRow >= len - 1) {
          this.currentRow--
        }
      }
    },

    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.row-sum {
  background-color: $gray-100;
  padding-right: 20px;
  display: flex;
  flex-wrap: nowrap;
  margin-top: -1px;

  .row-sum-td {
    flex: 1;
    padding: 0.5rem 0.25rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }
}
.tr-current {
  outline: 1px solid #c7c76d;
  outline-offset: -1px;

  td {
    border-bottom-color: #c7c76d;
  }
}
.input-td {
  background-color: #ffffee;
}
</style>
